<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/2/20
 * Time: 16:46
 */

namespace app\admin\controller;


use think\Db;
use think\Request;
use app\admin\model\Node;

class Comuser extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $where = [
                'user_status' => ['neq', 3],
                'user_verify' => 2,
                'user_type' => 2,
            ];
            if(session("company_id") > 0){
                $where['c_id'] = session("company_id");
            }
            if(isset($keyword) && $keyword != ''){
                $where['user_phone|user_username|user_job_desc'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword2) && $keyword2 != ''){
                $where['c_name|ct_name'] = ['like', '%' . $keyword2 . '%'];
            }
            if(isset($user_sex) && $user_sex != "")
            {
                $where['user_sex'] = $user_sex;
            }
            if(isset($user_status) && $user_status != "")
            {
                $where['user_status'] = $user_status;
            }
            if(isset($user_auth) && $user_auth != "")
            {
                $where['user_auth'] = $user_auth;
            }
            //注册时间查询
            if(isset($start) && $start != "" && isset($end) && $end == "")
            {
                $where['user_time'] = ['>=',$start];
            }
            if(isset($end) && $end != "" && isset($start) && $start == "")
            {
                $where['user_time'] = ['<=',$end];
            }
            if(isset($start) && $start != "" && isset($end) && $end != "")
            {
                $where['user_time'] = ['between',[$start,$end]];
            }
            //登录时间查询
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend == "")
            {
                $where['user_logintime'] = ['>=',$loginstart];
            }
            if(isset($loginend) && $loginend != "" && isset($loginstart) && $loginstart == "")
            {
                $where['user_logintime'] = ['<=',$loginend];
            }
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend != "")
            {
                $where['user_logintime'] = ['between',[$loginstart,$loginend]];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'u.*,c_name,ct_name';
            $count = Db::name('u_user')->alias('u')
                ->join('up_company c','u.user_hospital = c.c_id','left')
                ->join('up_company_team ct','u.user_room = ct.ct_id','left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('u_user')->alias('u')
                ->join('up_company c','u.user_hospital = c.c_id','left')
                ->join('up_company_team ct','u.user_room = ct.ct_id','left')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('user_time desc')
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $school = Db::table('up_u_user')
            ->field('user_hospital')
            ->group('user_hospital')
            ->select();
        $province = Db::table('up_area')
            ->field('district_id,district')
            ->where('pid',0)
            ->select();
        $this->assign([
            'school' => $school,
            'province' => $province,
        ]);
        return $this->fetch();
    }
    /**
     * 区域列表
     * @return mixed|\think\response\Json
     */
    public function userAreas(){
        if(request()->isAjax()){
            extract(input());
            $where = [
                'uc_user_id' => $user_id
            ];
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'uc.*,cp_name';
            $count = Db::name('user_charge')->alias('uc')
                ->join('up_company_product cp','uc.uc_cp_id = cp.cp_id','left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('user_charge')->alias('uc')
                ->join('up_company_product cp','uc.uc_cp_id = cp.cp_id','left')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('uc_update desc')
                ->field($field)
                ->select();
            if($lists){
                foreach ($lists as $k => $v){
                    $arr = explode(',',trim($v['uc_names'],','));
                    if($arr){
                        $str = '';
                        foreach ($arr as $k2 => $v2){
                            if((int)$v2 == 0){
                                $str .= $v2 . ',';
                            }
                        }
                        $lists[$k]['uc_names'] = trim($str,',');
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        $this->assign([
            'user_id' => $user_id,
        ]);
        return $this->fetch('comuser/areas');
    }

    /**
     * 新增区域
     * @return mixed|\think\response\Json
     */
    public function addArea(){
        if(Request::instance()->isPost()){
            extract(input());
            $have = Db::name('user_charge')
                ->where('uc_user_id',$user_id)
                ->where('uc_cp_id',$uc_cp_id)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '已经有此产品了！']);
            }
            Db::startTrans();
            try{
                $today = date('Y-m-d H:i:s');
                $insert = [
                    'uc_user_id' => $user_id,
                    'uc_cp_id' => $uc_cp_id,
                    'uc_time' => $today,
                    'uc_update' => $today,
                ];
                Db::name('user_charge')->insert($insert);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $user_id = input('user_id');
        $user_hospital = Db::name('u_user')->where('user_id',$user_id)->value('user_hospital');
        $datas = Db::name('company_product')
            ->where('cp_c_id',$user_hospital)
            ->where('cp_status',1)
            ->field('cp_name,cp_id')
            ->select();
        $this->assign([
            'datas' => $datas,
            'user_id' => $user_id
        ]);
        return $this->fetch('comuser/add_area');
    }
    /**
     * 编辑区域
     * @return mixed|\think\response\Json
     */
    public function editArea(){
        if(Request::instance()->isPost()){
            extract(input());
            $have = Db::name('user_charge')
                ->where('uc_user_id',$user_id)
                ->where('uc_cp_id',$uc_cp_id)
                ->where('uc_id','<>',$uc_id)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '已经有此产品了！']);
            }
            Db::startTrans();
            try{
                $today = date('Y-m-d H:i:s');
                $update = [
                    'uc_cp_id' => $uc_cp_id,
                    'uc_update' => $today,
                ];
                Db::name('user_charge')->where('uc_id',$uc_id)->update($update);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $uc_id = input('uc_id');
        $info = Db::name('user_charge')->where('uc_id',$uc_id)->find();
        $user_hospital = Db::name('u_user')->where('user_id',$info['uc_user_id'])->value('user_hospital');
        $datas = Db::name('company_product')
            ->where('cp_c_id',$user_hospital)
            ->where('cp_status',1)
            ->field('cp_name,cp_id')
            ->select();
        $this->assign([
            'datas' => $datas,
            'info' => $info
        ]);
        return $this->fetch('comuser/edit_area');
    }
    /**
     * 删除区域
     * @return \think\response\Json
     */
    public function delArea(){
        $uc_id = input('id');
        $res = Db::table('up_user_charge')->where('uc_id',$uc_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * [giveAccess 分配权限]
     * @return [type] [description]
     * @author
     */
    public function giveAccess()
    {
        $param = input('param.');
        //获取现在的权限
        if('get' == $param['type']){
            $where = [];
            $where['hos_status'] = 1;
            $shengs = Db::table('up_hospital')
                ->where($where)
                ->group('hos_sheng')
                ->column('hos_sheng');
            $shis = Db::table('up_hospital')
                ->where($where)
                ->group('hos_shi')
                ->column('hos_shi');
            $idarr = array_merge($shengs,$shis);
            $result = Db::table('up_area u')
                ->where('district_id','in',$idarr)
                ->order('level desc')
                ->field('district_id,district,pid')
                ->select();
            foreach($result as $key=>$vo){
                if($vo['pid'] > 0){
                    $datas = Db::table('up_hospital')
                        ->where($where)
                        ->where('hos_shi',$vo['district_id'])
                        ->group('hos_name')
                        ->field('hos_name district_id,hos_name district,hos_shi pid')
                        ->select();
                    $result = array_merge($result,$datas);
                }

            }
            //
            $rule = Db::table('up_user_charge')->where('uc_id',$param['id'])->value('uc_names');
            if(!empty($rule)){
                $rule = explode(',', trim($rule,','));
            }
            $str = "";
            foreach($result as $key=>$vo){
                //加个isParent:true，没有子节点时也显示文件夹
                $str .= '{ "id": "' . $vo['district_id'] . '", "pId":"' . $vo['pid'] . '", "name":"' . $vo['district'].'","isParent":true';
                if(!empty($rule)){
                    if(in_array($vo['district'], $rule) || in_array($vo['district_id'], $rule)){
                        $str .= ' ,"checked":1';
                    }
                }
                $str .= '},';
            }

            $resultdata = "[" . substr($str, 0, -1) . "]";
            return json(['code' => 200, 'data' => $resultdata, 'msg' => 'success']);
        }
        //分配新权限
        if('give' == $param['type']){
            $uc_id = $param['id'];
            $update = [
                'uc_names' => ',' . $param['rule'] . ',',
                'uc_update' => date('Y-m-d H:i:s'),
            ];
            if($param['rule'] == ''){
                return json(['code' => 100, 'msg' => '不能为空!']);
            }
            Db::startTrans();
            try{
                Db::name('user_charge')->where('uc_id',$uc_id)->update($update);
                $user_id = Db::name('user_charge')->where('uc_id',$uc_id)->value('uc_user_id');
                $chargeShi = Db::table('up_user_charge')
                    ->where('uc_user_id',$user_id)
                    ->field('uc_names')
                    ->select();
                $str = '';
                foreach ($chargeShi as $k => $v){
                    if($v['uc_names']){
                        $str .= trim($v['uc_names'],',') . ',';
                    }
                }
                $str = trim($str,',');
                $shistr = Db::name('hospital')
                    ->where('hos_name','in',$str)
                    ->group('hos_shi')
                    ->column('hos_shi');
                $shistr = implode($shistr,',');
                $update = [
                    'user_charge_shis' => ',' . $shistr . ',',
                    'user_updatetime' => date('Y-m-d H:i:s'),
                ];
                Db::name('u_user')->where('user_id',$user_id)->update($update);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
    }
//    public function giveAccess()
//    {
//        $param = input('param.');
//        //获取现在的权限
//        if('get' == $param['type']){
//            $where = [];
//            $where['user_type'] = 1;
//            $where['user_status'] = 1;
//            $where['user_verify'] = 2;
//            $shengs = Db::table('up_u_user')
//                ->where($where)
//                ->group('user_sheng')
//                ->column('user_sheng');
//            $shis = Db::table('up_u_user')
//                ->where($where)
//                ->group('user_shi')
//                ->column('user_shi');
//            $idarr = array_merge($shengs,$shis);
//            $result = Db::table('up_area u')
//                ->where('district_id','in',$idarr)
//                ->order('level desc')
//                ->field('district_id,district,pid')
//                ->select();
//            foreach($result as $key=>$vo){
//                if($vo['pid'] > 0){
//                    $datas = Db::table('up_u_user')
//                        ->where($where)
//                        ->where('user_shi',$vo['district_id'])
//                        ->group('user_hospital')
//                        ->field('user_hospital district_id,user_hospital district,user_shi pid')
//                        ->select();
//                    $result = array_merge($result,$datas);
//                }
//
//            }
//            //
//            $rule = Db::table('up_user_charge')->where('uc_id',$param['id'])->value('uc_names');
//            if(!empty($rule)){
//                $rule = explode(',', trim($rule,','));
//            }
//            $str = "";
//            foreach($result as $key=>$vo){
//                //加个isParent:true，没有子节点时也显示文件夹
//                $str .= '{ "id": "' . $vo['district_id'] . '", "pId":"' . $vo['pid'] . '", "name":"' . $vo['district'].'","isParent":true';
//                if(!empty($rule)){
//                    if(in_array($vo['district'], $rule) || in_array($vo['district_id'], $rule)){
//                        $str .= ' ,"checked":1';
//                    }
//                }
//                $str .= '},';
//            }
//
//            $resultdata = "[" . substr($str, 0, -1) . "]";
//            return json(['code' => 200, 'data' => $resultdata, 'msg' => 'success']);
//        }
//        //分配新权限
//        if('give' == $param['type']){
//            $uc_id = $param['id'];
//            $update = [
//                'uc_names' => ',' . $param['rule'] . ',',
//                'uc_update' => date('Y-m-d H:i:s'),
//            ];
//            if($param['rule'] == ''){
//                return json(['code' => 100, 'msg' => '不能为空!']);
//            }
//            Db::startTrans();
//            try{
//                Db::name('user_charge')->where('uc_id',$uc_id)->update($update);
//                $user_id = Db::name('user_charge')->where('uc_id',$uc_id)->value('uc_user_id');
//                $chargeShi = Db::table('up_user_charge')
//                    ->where('uc_user_id',$user_id)
//                    ->field('uc_names')
//                    ->select();
//                $str = '';
//                foreach ($chargeShi as $k => $v){
//                    if($v['uc_names']){
//                        $str .= trim($v['uc_names'],',') . ',';
//                    }
//                }
//                $str = trim($str,',');
//                $shistr = Db::name('u_user')
//                    ->where('user_hospital','in',$str)
//                    ->where('user_type',1)
//                    ->group('user_shi')
//                    ->column('user_shi');
//                $shistr = implode($shistr,',');
//                $update = [
//                    'user_charge_shis' => ',' . $shistr . ',',
//                    'user_updatetime' => date('Y-m-d H:i:s'),
//                ];
//                Db::name('u_user')->where('user_id',$user_id)->update($update);
//                Db::commit();
//                return json(['code' => 200, 'msg' => '成功']);
//            }catch(\Exception $e){
//                Db::rollback();
//                return json(['code' => 100, 'msg' => '失败']);
//            }
//        }
//    }
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function outExcel(){
        extract(input());
        set_time_limit(0);//防止超时
        $where = [
            'user_status' => ['neq', 3],
            'user_verify' => 2,
            'user_type' => 2,
        ];
        if(isset($keyword) && $keyword != ''){
            $where['user_phone|user_username|user_job_desc'] = ['like', '%' . $keyword . '%'];
        }
        if(isset($keyword2) && $keyword2 != ''){
            $where['c_name|ct_name'] = ['like', '%' . $keyword2 . '%'];
        }
        if(isset($user_sex) && $user_sex != "")
        {
            $where['user_sex'] = $user_sex;
        }
        if(isset($user_status) && $user_status != "")
        {
            $where['user_status'] = $user_status;
        }
        if(isset($user_auth) && $user_auth != "")
        {
            $where['user_auth'] = $user_auth;
        }
        //注册时间查询
        if(isset($start) && $start != "" && isset($end) && $end == "")
        {
            $where['user_time'] = ['>=',$start];
        }
        if(isset($end) && $end != "" && isset($start) && $start == "")
        {
            $where['user_time'] = ['<=',$end];
        }
        if(isset($start) && $start != "" && isset($end) && $end != "")
        {
            $where['user_time'] = ['between',[$start,$end]];
        }
        //登录时间查询
        if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend == "")
        {
            $where['user_logintime'] = ['>=',$loginstart];
        }
        if(isset($loginend) && $loginend != "" && isset($loginstart) && $loginstart == "")
        {
            $where['user_logintime'] = ['<=',$loginend];
        }
        if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend != "")
        {
            $where['user_logintime'] = ['between',[$loginstart,$loginend]];
        }
        if($ids){
            if($ids != 'all'){
                $where['user_id'] = ['in',$ids];
            }
        }else{
            return json(['code'=>0,'msg'=>'请选择数据！']);
        }
        $field = [
            'user_id','user_username','user_phone','user_sex', 'user_birthday',
            'c_name','ct_name','user_job_desc','user_auth','user_status',
            'user_time','user_logintime'
        ];
        $data = Db::name('u_user')->alias('u')
            ->join('up_company c','u.user_hospital = c.c_id','left')
            ->join('up_company_team ct','u.user_room = ct.ct_id','left')
            ->where($where)
            ->order('user_status asc,user_time desc')
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '用户ID', '姓名', '手机号', '性别', '生日',
                '所属公司', '所在团队', '简介', '所属角色', '状态',
                '注册时间', '最近登录时间'
            ];
            $status = ['user_sex','user_auth','user_status'];
            $values = [
                'user_sex' => [1 => '男',2 => '女'],
                'user_auth' => [1 => '业务员',2 => '区域负责人'],
                'user_status' => [1 => '正常',2 => '冻结']
            ];
            $res = exportExcel('comuserdata',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}